package igloo.ui;

import igloo.model.Archive;
import igloo.model.IVaultListener;
import igloo.model.Vault;

import javax.swing.table.AbstractTableModel;

public class ArchiveTableModel extends AbstractTableModel
{
    private static final long serialVersionUID = 1L;

    private Vault mVault;

    private final VaultListener mListener = new VaultListener();

    public ArchiveTableModel()
    {
    }

    public ArchiveTableModel(Vault vault)
    {
        setVault(vault);
    }

    public void setVault(Vault vault)
    {
        if(mVault != null)
            mVault.removeListener(mListener);

        mVault = vault;

        if(mVault != null)
            mVault.addListener(mListener);

        fireTableDataChanged();
    }

    @Override
    public int getRowCount()
    {
        int rowCount = 0;
        if(mVault != null)
            rowCount = mVault.getArchives().size();

        return rowCount;
    }

    @Override
    public int getColumnCount()
    {
        return 6;
    }

    @Override
    public String getColumnName(int column)
    {
        switch(column)
        {
            case 0:
                return "Name";

            case 1:
                return "Host";

            case 2:
                return "Path";

            case 3:
                return "Size";

            case 4:
                return "ID";
                
            case 5:
                return "";
        }

        return "";
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex)
    {
        if(mVault == null)
            return null;

        Archive archive = mVault.getArchives().get(rowIndex);
        switch(columnIndex)
        {
            case 0:
                return archive.getName();
            case 1:
                return archive.getHostName();
            case 2:
                return archive.getPath();
            case 3:
                return archive.getSize();
            case 4:
                return archive.getId();
        }

        return null;
    }

    public Archive getArchiveAt(int rowIndex)
    {
        if(mVault == null)
            return null;

        return mVault.getArchives().get(rowIndex);
    }

    private class VaultListener implements IVaultListener
    {
        @Override
        public void archiveAdded(Vault vault, Archive archive)
        {
            fireTableDataChanged();
        }

        @Override
        public void archiveRemoved(Vault vault, Archive archive)
        {
            fireTableDataChanged();
        }

        @Override
        public void vaultUpdated(Vault vault)
        {
        }
    }
}
